﻿using AntdUI;
using MobileControlGuru.Src;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static MobileControlGuru.AutoTask.TaskJson;

namespace MobileControlGuru.AutoTask
{
    public partial class MultiTaskEdit : MobileControlGuru.BaseForm
    {
        public List<TaskOperateTemp> taskOperateTemps;
        public MultiTaskEdit()
        {
            InitializeComponent();
        }

        private void MultiTaskEdit_Load(object sender, EventArgs e)
        {
            this.dateTimePickerEnd.Format = DateTimePickerFormat.Time;


            this.dateTimePickerStart.Format = DateTimePickerFormat.Time;
            this.InitCheckBoxDevice();
            InitDatetimePicker();

            this.inputNumberWorkTime.Text = "90";
            this.inputNumberWorkTime.Value = 90;
        }
        #region 设备选择
        private void checkedListBoxDevice_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        #endregion

        private void btnAddOperateItem_Click(object sender, EventArgs e)
        {
            var edit = new TaskItemTemp();
            edit.deleteTempEevnt += ItemDelete;
            edit.checkItemTempDelegate += checkboxitemEvent;
            this.flowLayoutPanelOperate.Controls.Add(edit);
            UpdateItemIndex();
        }
        public void ItemDelete(int index)
        {
            UpdateItemIndex();
        }
        private void UpdateItemIndex()
        {
            int i = 0;
            foreach (TaskItemTemp c in this.flowLayoutPanelOperate.Controls)
            {
                c.SetIndex(++i);
            }
        }
        private void InitTaskOperateTemps(List<TaskOperateTemp> taskOperateTemps)
        {
            foreach (var item in taskOperateTemps)
            {
                var edit = new TaskItemTemp(item);
                edit.deleteTempEevnt += ItemDelete;
                edit.checkItemTempDelegate += checkboxitemEvent;
                this.flowLayoutPanelOperate.Controls.Add(edit);

            }

        }
        public void checkboxitemEvent(bool isChecked, int index)
        {
            Console.WriteLine($"checkboxitemEvent  {isChecked},{index}");

            foreach (TaskItemTemp c in this.flowLayoutPanelOperate.Controls)
            {
                if (isChecked && c.Index == index)
                {
                    c.checkBoxMulti.Checked = true;
                }
                else
                {
                    c.checkBoxMulti.Checked = false;
                }

            }
        }
        private void InitDatetimePicker()
        {
            int count_device = DeviceManager.Instance.devices.Count;

            DateTime? starttime = TaskJson.GetLatestEndDateTime(TaskJson.Instance.tasks);
            if (starttime != null)
            {
                DateTime dt = (DateTime)starttime;
                this.dateTimePickerStart.Value = dt.AddMinutes(2);
                this.dateTimePickerEnd.Value = dt.AddMinutes(count_device * 2);
            }
            else
            {
                this.dateTimePickerStart.Value = DateTime.Now.AddMinutes(5);
                this.dateTimePickerEnd.Value = DateTime.Now.AddMinutes(count_device * 2 + 5);
            }

        }
        private void InitCheckBoxDevice()
        {
            foreach (var d in DeviceManager.Instance.devices)
            {

                this.checkedListBoxDevice.Items.Add(d.Name);

                Console.WriteLine(d.Name);
            }



        }
        private void btnExportOperateTemp_Click(object sender, EventArgs e)
        {
            List<TaskOperateTemp> list = GetTaskOperateTemps();
            // 序列化数据到JSON字符串
            string jsonData = JsonConvert.SerializeObject(list, Formatting.Indented);
            // 创建SaveFileDialog实例并配置
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "JSON (*.json)|*.json|所有文件 (*.*)|*.*";
            saveFileDialog.Title = "导出多参数批量数据";
            saveFileDialog.FileName = $"导出多参数批量数据_{DateTime.Now.ToString("yyyyMMddHHmmss")}"; // 默认文件名

            // 显示保存对话框并获取用户选择
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {


                try
                {
                    File.WriteAllText(saveFileDialog.FileName, jsonData);

                    MessageBox.Show("数据导出成功！");
                }
                catch (Exception ex)
                {
                    // 处理文件写入过程中的异常
                    MessageBox.Show($"导出失败：{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 获取当前所有操作模板
        /// </summary>
        /// <returns></returns>
        private List<TaskOperateTemp> GetTaskOperateTemps()
        {
            List<TaskOperateTemp> taskOperateTemps = new List<TaskOperateTemp>();
            foreach (TaskItemTemp item in this.flowLayoutPanelOperate.Controls)
            {
                item.taskOperateTemp = item.GetTaskOperateTemp();
                if (item.taskOperateTemp != null)
                {
                    taskOperateTemps.Add(item.taskOperateTemp);

                    Console.WriteLine($"{item.taskOperateTemp.Param}{item.taskOperateTemp.isBase}");
                    if (item.taskOperateTemp.VariableParams != null)
                    {
                        foreach (var itemparams in item.taskOperateTemp.VariableParams)
                        {
                            Console.WriteLine($"VariableParams: {itemparams.TempParam}");
                        }

                    }
                }
                


            }
            return taskOperateTemps;
        }
        private void btnImportOperateTemp_Click(object sender, EventArgs e)
        {
            // 使用OpenFileDialog让用户选择JSON文件
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "JSON files (*.json)|*.json",
                DefaultExt = "json"
            };

            // 如果用户选择了文件并点击了“打开”
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 读取JSON文件的内容
                    string jsonFilePath = openFileDialog.FileName;
                    string jsonData = File.ReadAllText(jsonFilePath);

                    // 反序列化JSON字符串到对象列表
                    List<TaskOperateTemp> dataList = JsonConvert.DeserializeObject<List<TaskOperateTemp>>(jsonData);

                    // 使用dataList中的数据
                    // 例如，将其显示在DataGridView或其他控件中
                    InitTaskOperateTemps(dataList);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导入失败：{ex.Message}");
                }
            }
        }
        #region 删除操作

        #endregion
        private void btnDeleteOperate_Click(object sender, EventArgs e)
        {

        }

        private void btnClear_Click(object sender, EventArgs e)
        {

            this.flowLayoutPanelOperate.Controls.Clear();
            this.taskOperateTemps = null;
        }
        #region 批量生成
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            btnGenerate.Text = "进行排班。。。。。。。。";
            string[] checkdevices = this.GetCheckedDevices();
            if (checkdevices.Length == 0)
            {
                MessageBox.Show("未选中任何设备");
                return;
            }
            taskOperateTemps = GetTaskOperateTemps();
            TaskOperateTemp mainVirableTemp = taskOperateTemps.Where(p => p.isBase == true).FirstOrDefault();
            if (mainVirableTemp == null)
            {
                MessageBox.Show("没有设置任何参数");
                return;
            }
            int WorkTime = 90;
            if (!string.IsNullOrEmpty(inputNumberWorkTime.Text)) WorkTime = Convert.ToInt32(inputNumberWorkTime.Text);
            Task.Run(() =>
            {
              
                Random random = new Random();
 
                //现根据主要参数生成多条任务
                foreach (var variableitem in mainVirableTemp.VariableParams)
                {
                    
                    if (!string.IsNullOrEmpty(variableitem.TempParam))
                    {

                        List<ReferenceSource> referenceSource = new List<ReferenceSource>();


                        List<TaskItem> taskItemsTemp = new List<TaskItem>();
                        for (int i = 0; i < taskOperateTemps.Count; i++)
                        {
                            TaskOperateTemp taskOperateTemp = taskOperateTemps[i];
                            TaskItem taskItem;
                            if (taskOperateTemp.isBase)
                            {
                                taskItem = new TaskJson.TaskItem()
                                {
                                    Oprate = taskOperateTemp.Oprate,
                                    Param = variableitem.TempParam,
                                    IsAdb = taskOperateTemp.IsAdb,
                                    Note = taskOperateTemp.Note
                                };
                            }
                            else
                            {
                                //外部数据源
                                if (taskOperateTemp.isReference)
                                {
                                    if (taskOperateTemp.referenceSource.Count > 0)
                                    {
                                        referenceSource = taskOperateTemp.referenceSource;
                                        ////// 使用 RandomNumberGenerator 生成一个随机索引
                                        //byte[] randomBytes = new byte[4]; // 假设我们使用一个 32 位的随机数
                                        //using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
                                        //{
                                        //    rng.GetBytes(randomBytes);
                                        //    // 注意：这里我们简单地将字节数组转换为 int，但实际上需要更复杂的处理来确保索引在有效范围内
                                        //    // 这里只是为了演示，因此假设数组长度不会超过 int.MaxValue，并且随机生成的数会被模运算限制在数组长度内
                                        //    int index = BitConverter.ToInt32(randomBytes, 0) % taskOperateTemp.referenceSource.Count;
                                        //    // 确保索引是非负的（虽然在这个例子中由于模运算结果总是非负的，这一步是多余的）
                                        //    index = index < 0 ? index + taskOperateTemp.referenceSource.Count : index;

                                        //    // 使用随机索引从数组中获取对象

                                        //    ReferenceSource randomElement = taskOperateTemp.referenceSource[index];
                                        //    taskItem = new TaskJson.TaskItem()
                                        //    {
                                        //        Oprate = taskOperateTemp.Oprate,
                                        //        Param = randomElement.RContent,
                                        //        IsAdb = taskOperateTemp.IsAdb,
                                        //        Note = taskOperateTemp.Note
                                        //    };
                                        //    // 输出结果
                                        //    Console.WriteLine($"随机获取的对象是: {randomElement.RContent}");
                                        //}

                                        //////按顺序分配

                                        //// 遍历array1的每个元素，并使用array2中的元素来填充它
                                        //// 使用取模运算来处理array2中元素不足的情况
                                        //// 使用取模运算确保索引在array2的有效范围内内循环
                                        //int indexInArray2 = j % taskOperateTemp.referenceSource.Count;
                                        //ReferenceSource randomElement = taskOperateTemp.referenceSource[indexInArray2];
                                        //taskItem = new TaskJson.TaskItem()
                                        //{
                                        //    Oprate = taskOperateTemp.Oprate,
                                        //    Param = randomElement.RContent,
                                        //    IsAdb = taskOperateTemp.IsAdb,
                                        //    Note = taskOperateTemp.Note
                                        //};
                                        taskItem = new TaskJson.TaskItem()
                                        {
                                            Oprate = taskOperateTemp.Oprate,
                                            Param = taskOperateTemp.Param,
                                            IsAdb = taskOperateTemp.IsAdb,
                                            Note = "referenceSource"
                                        };
                                    }
                                    else
                                    {
                                        taskItem = new TaskJson.TaskItem()
                                        {
                                            Oprate = taskOperateTemp.Oprate,
                                            Param = taskOperateTemp.Param,
                                            IsAdb = taskOperateTemp.IsAdb,
                                            Note = taskOperateTemp.Note
                                        };
                                    }
                                   
                                }
                                else
                                {
                                    taskItem = new TaskJson.TaskItem()
                                    {
                                        Oprate = taskOperateTemp.Oprate,
                                        Param = taskOperateTemp.Param,
                                        IsAdb = taskOperateTemp.IsAdb,
                                        Note = taskOperateTemp.Note
                                    };
                                }
                              
                            }
                           
                            taskItemsTemp.Add(taskItem);

                        }
                       
                        DateTime starttime = this.dateTimePickerStart.Value;
                        DateTime endtime = this.dateTimePickerEnd.Value;

                        string[] devicenames = GetCheckedDevices();
                        string tempworkcontent = String.Join(",", devicenames);
                        List<ScheduleDevice> selectDevices = new List<ScheduleDevice>();
                        foreach (var item in devicenames)
                        {
                            ScheduleDevice d = new ScheduleDevice();
                            d.Name = item;
                            d.WorkContent = tempworkcontent;
                            selectDevices.Add(d);
                        }

                        if(variableitem.Amount == 0)
                        {
                            variableitem.Amount = selectDevices.Count;
                        }
                        // 确保元素数量足够
                        if (selectDevices.Count > variableitem.Amount)
                        {
                            // 使用Random类生成x个不重复的随机索引
                            Random randomDevice = new Random();
                            List<int> indices = Enumerable.Range(0, selectDevices.Count).OrderBy(i => random.Next()).Take(variableitem.Amount).ToList();

                            // 根据随机索引选取对应的ScheduleDevice对象
                            List<ScheduleDevice> newDevices = new List<ScheduleDevice>();
                            foreach (int index in indices)
                            {
                                newDevices.Add(selectDevices[index]);
                            }

                            TaskJson.TaskRandom(starttime, endtime, newDevices, taskItemsTemp, random,referenceSource,WorkTime);
                        }
                        else
                            TaskJson.TaskRandom(starttime, endtime, selectDevices, taskItemsTemp, random, referenceSource, WorkTime);
                    }

                }

                this.Invoke((MethodInvoker)delegate
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                });
            });



        }
        #endregion

        private void btnAllCheck_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.checkedListBoxDevice.Items.Count; i++)
            {
                this.checkedListBoxDevice.SetItemChecked(i, true);
            }
        }

        private void btnUnAllCheck_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.checkedListBoxDevice.Items.Count; i++)
            {
                this.checkedListBoxDevice.SetItemChecked(i, false);
            }
        }
        private string[] GetCheckedDevices()
        {
            List<string> Devices = new List<string>();
            // 通过遍历获取选中的项
            foreach (string item in this.checkedListBoxDevice.CheckedItems)
            {
                Devices.Add(item);
                Console.WriteLine(item);
            }

            return Devices.ToArray();
        }
        private int[] GetCheckedItemIndexs()
        {
            List<int> itemIndexs = new List<int>();
            // 通过索引获取选中的项
            for (int i = 0; i < this.checkedListBoxDevice.CheckedIndices.Count; i++)
            {
                int index = this.checkedListBoxDevice.CheckedIndices[i];
                Console.WriteLine(this.checkedListBoxDevice.Items[index]);

                itemIndexs.Add(index);
            }
            return itemIndexs.ToArray();
        }
    }
}
